package com.frank.towerrush.view;

import java.util.ArrayList;
import java.util.List;

import com.frank.towerrush.R;
import com.frank.towerrush.split.Bullet;
import com.frank.towerrush.split.Flag;
import com.frank.towerrush.split.Monster;
import com.frank.towerrush.split.Tower;
import com.frank.towerrush.util.SystemParameter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;

public class GameView extends BaseSurfaceView {

    Bitmap bitmap;
    RectF dst;

    List<Flag> flags;
    List<Monster> monsters;
    List<Bullet> bullets;
    Tower tower;
    int timer = 0;

    public GameView(Context context, Bitmap bitmap, List<Flag> flags) {
        super(context);
        refresh = REFRESH_SPEED_SLOW;
        this.bitmap = bitmap;
        dst = new RectF(0, 0, SystemParameter.screenWidth, SystemParameter.screenHeight);
        Monster.setPath(flags);

        tower = new Tower("", "", BitmapFactory.decodeResource(getResources(), R.drawable.tower02),
                BitmapFactory.decodeResource(getResources(), R.drawable.b2), 1000, 1000);

        monsters = new ArrayList<Monster>();
        bullets = new ArrayList<Bullet>();
        Tower.setMonsterList(monsters);
        Bullet.setBulletList(bullets);

        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setDither(true);
        paint.setAntiAlias(true);
    }

    private void newMonster() {
        Monster monster = new Monster(getContext(), R.drawable.en51);
        monsters.add(monster);
    }

    @Override
    public void onUpdate() {
        timer += refresh;
        if (monsters.size() < 5 && timer == refresh * 10) {
            newMonster();
            timer = 0;
        }
    }

    @Override
    public void onPaint(Canvas canvas, Paint paint) {
        // 绘制地图
        canvas.drawBitmap(bitmap, null, dst, paint);
        // 绘制怪物

        for (Monster m : monsters) {
            if (m.isDead()) {
                monsters.remove(m);
                continue;
            }
            m.paint(canvas, paint);
        }
        // 绘制塔
        tower.paint(canvas, paint, refresh, bullets);
        // 绘制子弹
        for (Bullet b : bullets) {
            if (!monsters.contains(b.target)) {
                bullets.remove(b);
                continue;
            }
            b.paint(canvas, paint);
        }
    }

}
